<template>
  <div class="shopping-cart-container">
    <!-- 导航栏 -->
    <Navigator @returnUserInfo="getUserInfo"></Navigator>
    <!-- 主体 -->
    <div class="main">
      <!-- 购物车列表头部信息 -->
      <div class="cart-header">
        <h2 class="left">购物车（全部{{ cartList.length }}）</h2>
        <div class="right">
          <span>已选商品（不含运费）</span>
          <span class="total">{{ totalPrice }}</span>
          <el-button
            ref="settleButton"
            :disabled="settleIsDisable"
            class="settle-account"
            type="info"
            round
            @click="handleGenerateOrder"
            >结算</el-button
          >
        </div>
      </div>
      <!-- 商品信息 -->
      <el-table
        ref="cartTable"
        :data="cartList"
        tooltip-effect="dark"
        style="width: 100%"
        @select="handleSelectChange"
        @select-all="selectAllCheckedBox"
      >
        <template slot="empty">
          <img src="@/assets/cart/empty-cart.png" />
          <span>您的购物车还是空的，赶紧行动吧！</span>
        </template>
        <el-table-column align="center" type="selection"> </el-table-column>
        <el-table-column label="商品信息" class-name="commodity-info">
          <template slot-scope="scope">
            <el-popover
              :open-delay="300"
              placement="right"
              width="240"
              trigger="hover"
            >
              <el-image
                slot="reference"
                :src="scope.row.image"
                class="goods-img"
              ></el-image>
              <el-image :src="scope.row.image" class="goods-img"></el-image>
            </el-popover>

            <el-tooltip
              :open-delay="300"
              effect="light"
              :content="scope.row.gName"
              placement="top-start"
            >
              <div class="goods-name">{{ scope.row.gName }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          class-name="single-price"
          prop="discountPrice"
          label="单价"
          width="130"
        >
          <template slot-scope="scope">
            <span
              class="original-price"
              v-if="scope.row.originalPrice != scope.row.discountPrice"
              >￥{{ scope.row.originalPrice }}</span
            >
            <span class="discount-price">￥{{ scope.row.discountPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column
          class-name="amount"
          label="数量"
          width="120"
          align="center"
        >
          <el-input-number
            size="mini"
            slot-scope="scope"
            v-model="scope.row.amount"
            @change="onHandleAmountChange($event, scope)"
            :min="1"
            label="描述文字"
          ></el-input-number>
        </el-table-column>
        <el-table-column
          label="金额"
          width="140"
          align="center"
          class-name="price"
        >
          <template slot-scope="scope">
            ￥{{ (scope.row.amount * scope.row.discountPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          class-name="operator"
          align="center"
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <a href="javascript:void(0);">移入收藏夹</a>
            <a
              href="javascript:void(0);"
              @click="onDeleteCartGoods(scope.row, false)"
              >删除</a
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 购物车列表底部信息 -->
      <div class="cart-bottom">
        <div class="left">
          <span class="del" @click="onDeleteCartGoods($event, true)">删除</span>
          <span class="to-collection">移入收藏夹</span>
        </div>
        <div class="right">
          <span class="selected-goods"
            >已选商品 <span class="num">{{ selectedCount }}</span> 件</span
          >
        </div>
      </div>
    </div>
    <!-- 脚部 -->
    <Footert />
  </div>
</template>

<script>
import Navigator from "@/components/navigator";
import Footert from "@/components/footer";
import {
  getCartItems,
  changeChecked,
  changeAllChecked,
  deleteCartGoods,
  updateGoodsAmount,
} from "@/api/cart";
import { generateOrder } from "@/api/order";

export default {
  name: "ShoppingCartIndex",
  props: {},
  components: { Navigator, Footert },
  data() {
    return {
      cartList: [], // 用户购物车信息
      userInfo: {}, // 用户信息
      settleIsDisable: true, // 结算按钮是否可点击
    };
  },
  created() {},
  mounted() {},
  methods: {
    // 加载购物车信息
    async loadUserCartList() {
      let userId = this.userInfo.userId;
      let { data } = await getCartItems(userId);
      if (Number(data.code) === 200) {
        this.cartList = data.data;
        this.initSelectionChecked();
      }
    },
    // 初始化购物车商品是否选中状态
    initSelectionChecked() {
      this.$nextTick(() => {
        for (let i = 0; i < this.cartList.length; i++) {
          if (this.cartList[i].checked == 1) {
            this.$refs.cartTable.toggleRowSelection(this.cartList[i]);
          }
        }
      });
    },
    // 改变商品的选中状态
    async handleSelectChange(selectedItemList, row) {
      let res = selectedItemList.length && selectedItemList.indexOf(row) !== -1; //为true时选中，为 0 时（false）未选中
      if (res) {
        const { data } = await changeChecked({
          gId: row.gId,
          userId: row.userId,
          checked: 1,
        });
        if (Number(data.code) !== 200) {
          this.$message.error(data.msg);
          return;
        }
        row.checked = 1;
      } else {
        const { data } = await changeChecked({
          gId: row.gId,
          userId: row.userId,
          checked: 0,
        });
        if (Number(data.code) !== 200) {
          this.$message.error(data.msg);
          return;
        }
        row.checked = 0;
      }
    },
    // 接收导航栏返回的userInfo
    getUserInfo(userInfo) {
      this.userInfo = userInfo;
      // 加载用户购物车数据
      this.loadUserCartList();
    },
    // 处理手动修改商品数量时的错误
    async onHandleAmountChange(value, scope) {
      if (!value) {
        value = 1;
        this.$nextTick(() => {
          this.cartList[scope.$index]["amount"] = 1;
        });
      }
      const { data } = await updateGoodsAmount({
        userId: this.userInfo.userId,
        gId: scope.row.gId,
        amount: value,
      });
      if (Number(data.code) !== 200) {
        return this.$message.error("修改商品数量失败");
      }
    },
    // 设置商品状态为全选
    async selectAllCheckedBox(itemList) {
      let checked;
      if (itemList.length > 0) {
        checked = 1;
      } else {
        checked = 0;
      }
      // 修改所有商品选中状态
      let { data } = await changeAllChecked({
        userId: this.userInfo.userId,
        cartGoodsList: this.cartList,
        checked: checked,
      });
      if (Number(data.code) !== 200) {
        return this.$message.error(data.msg);
      }
      // 更改页面上选中框状态
      this.cartList.forEach((item) => {
        item.checked = checked;
      });
    },
    // 删除购物车中商品
    async onDeleteCartGoods(goods, batch) {
      if (batch) {
        this.$confirm("确定要删除所选中的商品吗？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            let selectedItemList = this.cartList.filter((item) => {
              return item.checked == 1;
            });
            if (selectedItemList.length <= 0) {
              this.$message("请选择你要删除的商品");
            }
            const { data } = await deleteCartGoods({
              userId: this.userInfo.userId,
              cartGoodsList: [...selectedItemList],
            });
            if (Number(data.code) !== 200) {
              this.$message.error("删除商品失败！");
              return;
            }
            // 删除成功
            this.loadUserCartList();
          })
          .catch(() => {
            console.log("已取消删除");
          });
      } else {
        this.$confirm("确定要删除这条商品吗？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const { data } = await deleteCartGoods({
              userId: this.userInfo.userId,
              cartGoodsList: [goods],
            });
            if (Number(data.code) !== 200) {
              this.$message.error("删除商品失败！");
              return;
            }
            // 删除成功
            this.loadUserCartList();
          })
          .catch(() => {
            // 用户点击了取消按钮
            console.log("已取消删除");
          });
      }
    },
    // 结算生成订单
    handleGenerateOrder() {
      this.$confirm("您确定要提交订单吗？")
        .then(async () => {
          const { data } = await generateOrder({
            userId: this.userInfo.userId,
            orderItemList: this.cartList,
          }, true);
          if (Number(data.code) === 200) {
            this.$message.success("提交订单成功");
            // 重新加载购物车信息
            this.loadUserCartList();
          }
        })
        .catch(() => {
          console.log("取消提交订单");
        });
    },
  },
  computed: {
    // 选中商品的总价格
    totalPrice() {
      return this.cartList.reduce((sum, e) => {
        let amount = e.amount;
        let discountPrice = e.discountPrice;
        if (e.checked) {
          sum = (
            parseFloat(sum) + parseFloat((amount * discountPrice).toFixed(2))
          ).toFixed(2);
        }
        return sum;
      }, 0);
    },
    selectedCount() {
      return this.cartList.reduce((sum, e) => {
        if (e.checked) {
          return sum + 1;
        }
        return sum;
      }, 0);
    },
  },
  watch: {
    cartList: {
      // immediate: true,
      deep: true,
      handler(newValue) {
        newValue.forEach((item) => {
          if (item.checked) {
            this.settleIsDisable = false;
            this.$refs["settleButton"].$el.style.backgroundColor = "#ff5000";
            return;
          }
        });
        let res = newValue.every((item) => {
          return item.checked == 0;
        });
        if (res) {
          this.settleIsDisable = true;
          this.$refs["settleButton"].$el.style.backgroundColor = "#aaa";
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
.shopping-cart-container {
  :deep(.main) {
    position: relative;
    font: 12px/1.5 tahoma, arial, "Hiragino Sans GB", "\5b8b\4f53", sans-serif;
    // width: 70%;
    width: 990px;
    background-color: #fff;
    margin: 24px auto 0;
    min-height: 400px;
    border-radius: 24px;
    padding-bottom: 72px;
    .cart-header {
      line-height: 72px;
      padding: 0 18px;
      border-bottom: 1px solid #e6e6e6;
      display: flex;
      justify-content: space-between;
      .left {
        font-size: 18px;
      }
      .right {
        display: flex;
        align-items: center;
        font-size: 14px;
        .total {
          font-family: Arial, Verdana;
          font-weight: 500;
          margin-right: 12px;
          font-size: 22px;
          color: #ff5000;
        }
        .settle-account {
          width: 74px;
          height: 42px;
        }
      }
    }

    .el-table {
      font-size: 12px;
      .el-table__row {
        .commodity-info {
          .cell {
            display: flex;
            align-items: center;

            .goods-img {
              margin-right: 10px;
              width: 80px;
            }
            .goods-name {
              cursor: pointer;
              width: 200px;
              height: 42px;
              text-overflow: -o-ellipsis-lastline;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }
            .goods-name:hover {
              color: #fe6600;
              text-decoration: underline;
            }
          }
        }
        .single-price {
          .cell {
            font-size: 12px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            .original-price {
              text-decoration: line-through;
              color: #9c9c9c;
            }
            .discount-price {
              font-weight: 700;
              color: #3c3c3c;
            }
          }
        }
        .amount {
          .cell {
            .el-input-number {
              width: 100px;
            }
          }
        }
        .price {
          color: #f40;
          font-weight: 700;
        }
        .operator {
          .cell {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: flex-start;

            a:hover {
              color: #fe6600;
              text-decoration: underline;
            }
          }
        }
        background-color: #f5f5f5;
        border-radius: 25px;
      }
      .el-table__empty-text {
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .cart-bottom {
      position: absolute;
      bottom: 0;
      background: white;
      border-radius: 0 0 24px 24px;
      font-size: 14px;
      width: 100%;
      height: 72px;
      line-height: 72px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .left {
        .del,
        .to-collection {
          margin-left: 20px;
          cursor: pointer;
        }
        .del:hover,
        .to-collection:hover {
          color: #fe6600;
          text-decoration: underline;
        }
      }
      .right {
        font-size: 20px;
        font-weight: 700;
        .selected-goods {
          margin-right: 35px;
          .num {
            color: #ff4400;
          }
        }
      }
    }
  }
}
</style>
